var base = require('./base');
import Config from '../utils/config';

export default{
    //向指定表中插入数据
    insertData: async (data,table) => {
        //let result = await base.connectDB();
        let result = Config.MONGODB_DB;
        if(result){
            var collection = result.collection(table);
            return new Promise((resolve)=>{
                collection.insert(data, function(err, result) {
                    if(err)
                    {
                        resolve(false);
                        return;
                    }
                    resolve(true);
                });
            })
        }
    },

    //在指定表中查找数据
    findData: async (data,table) => {
        //let result = await base.connectDB();
        let result = Config.MONGODB_DB;
        if(result){
            var collection = result.collection(table);
            return new Promise((resolve)=>{
                collection.find(data).sort({KEY:-1}).toArray(
                    function (err,result) {
                        if(!err){
                            resolve(result)
                        }else{
                            // console.log('findError',err)
                        }
                    }
                )
            })

        }

    },

    //分页查询 rows每次查询的数量 skip查询的页数
    findDataPage: async (data,table,rows,skip) => {
        //let result = await base.connectDB();
        let result = Config.MONGODB_DB;
        if(result){
            var collection = result.collection(table);
            return new Promise((resolve)=>{
                collection.find(data).limit(rows).skip(skip).sort({serverTime:-1}).toArray(
                    function (err,result) {
                        if(!err){
                            resolve(result)
                        }else{
                            //console.log('findDataPageError',err)
                        }
                    }
                )
            })

        }

    },

    //更新指定表数据
    updateData: async (keyData,UpdateData,table) => {
        //let result = await base.connectDB();
        let result = Config.MONGODB_DB;
        if(result){
            let collection = result.collection(table);
            return new Promise((resolve)=>{
                collection.update(keyData,{$set:UpdateData},{multi:true},function (err,result) {
                    //console.log(err,result)
                    if(!err){
                        resolve(true)
                    }else{
                        resolve(false)
                    }
                })
            })
        }

    },

    //连接数据库
    connectMongo: async ()=>{
        let result = await base.connectDB();
        if(!result){
            Config.MONGODB_DB = false;
            return;
        }
        //console.log(result)
        Config.MONGODB_DB = result;
    }

}